﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using com.guojin.mj.net.message.game;
using com.guojin.mj.net.message.login;
using com.guojin.mj.net.message.club;
using com.guojin.mj.net.message;
using DG.Tweening;
using System;

public enum ButtonName
{
   startBtn,
   readyBtn,
   inviteBtn,  
}

public class GameRoomPage : EventManager
{
    private static GameRoomPage instance;
    public static GameRoomPage GetInstance()
    {
        return instance;
    }
    void Awake()
    {
        instance = this;
    }

    public override void InformationSetting()
    {
        GameObject cav = GameObject.Find("Canvas").gameObject;
        aud = cav.transform.GetComponents<AudioSource>()[0];
        aud2 = cav.transform.GetComponents<AudioSource>()[1];

        //morebtn1  退出
        AddListenerToButton(moreSetBtn, MoreBtnClick);
        AddListenerToButton(exitBtn, ExitBtnClick);

        //准备 开始 邀请按钮
        AddListenerToButton(readyBtn, readyBtnClick);
        AddListenerToButton(startBtn, StartBtnClick);
        AddListenerToButton(inviteBtn, InviteBtnClick);

        GameRoomModel.GetInstance().RoomIDChangeEvent += SetRoomID;
        GameRoomModel.GetInstance().ChapterChangeEvent += SetChapter;
        GameRoomModel.GetInstance().currentSingleBetChangeEvent += SetSingleBet;
        GameRoomModel.GetInstance().CurrentTotalBetChangeEvent += SetTotalBet;

    }

    // 0 筹码移动   1 下注（少） 2 下注（多） 3 发牌   4 亮牌  5准备  6 slider点击 7发牌桌面 8 未知
    public  AudioClip[] clips;
    private  AudioSource aud;
    //播放胜利和失败音效
    private  AudioSource aud2;

    //播放聚锅动画
    public void SetJvGuoAni(bool show)
    {
        if (show)
        {
            TooL.LoadPrefab(DealPanel, "JvGuoAni");
        }
    }

    //top
    public Button moreSetBtn;
    public Button exitBtn;

    //btnGroup
    public Button startBtn;
    public Button readyBtn;
    public Button inviteBtn;
    public Button voiceBtn;
    public Button chatBtn;

    #region // scoreGroup(singBet totalBet ,Model状态改变事件监听)
    public Text singleBetTex;
    public Text totalBetTex;

    private void SetSingleBet(int singleBet)
    {
        if (GameObject.Find("GameRoomPage(Clone)") && singleBetTex != null)
            singleBetTex.text = string.Format("{0}", singleBet.ToString());
        else
            Debug.Log("重置singleBet没有找到GameRoomPage(Clone)面板！");
    }

    private void SetTotalBet(int totalBet)
    {
        if (GameObject.Find("GameRoomPage(Clone)") && totalBetTex != null)
            totalBetTex.text = string.Format("{0}", totalBet.ToString());
        else
            Debug.Log("重置totalBet没有找到GameRoomPage(Clone)面板！");
    }
    #endregion

    #region //ruleGroup(roomId，chapter,Model状态改变事件监听)
    public Text roomIDTex;
    public Text chapterTex;

    private void SetRoomID(string roomID)
    {
        if (GameObject.Find("GameRoomPage(Clone)")&& roomIDTex != null)
            SetText(roomIDTex, string.Format("房间号：{0}", roomID));
        else
            Debug.Log("重置RoomId没有找到GameRoomPage(Clone)面板！");
    }

    private void SetChapter(int currentChapter, int maxChapter)
    {
        if (GameObject.Find("GameRoomPage(Clone)") && chapterTex != null)
            chapterTex.text = string.Format("局数：{0}/{1}", currentChapter.ToString(), maxChapter.ToString());
        else
            Debug.Log("重置chapterTex没有找到GameRoomPage(Clone)面板！");
    }
    #endregion

    #region//规则面板  Controller直接调用设置
    public Text ruleTex1;
    public Text ruleTex2;
    public void SetRuleTex1(string str)
    {
        ruleTex1.text = str;
    }
    public void SetRuleTex2(string str)
    {
        ruleTex2.text = str;
    }
    #endregion

    public GameObject[] loadPointGroup;
    public GameObject moreBtnPage;

    //发牌动画的Panel
    public GameObject panel;
    public GameObject DealPanel;

    private void ClearLoadPointGroup()
    {
        foreach (var item in loadPointGroup)
        {
            for (int i = 0; i < item.transform.childCount; i++)
            {
                if (item.transform.GetChild(i).childCount > 0)
                {
                    TooL.DestroyAllChildren(item.transform.GetChild(i).gameObject);
                }
            }
        }
    }

    private  void MoreBtnClick()
    {
        if (moreBtnPage.activeInHierarchy)
            moreBtnPage.SetActive(false);
        else
            moreBtnPage.SetActive(true);
    }

    public void ExitBtnClick()                           //12,23 提交解散房间    12,21 某个玩家发起投票（id，name）,  12,22 发送投票结果（Result, id）
    {
        if (GameRoomModel.GetInstance().RoomState == 0)
        {
            if (GameData.GetInstance().locationIndex != 0)
            {
                TooL.ShowTipsPage("确认退出房间?", TooL.TipsPageType.haveCancelPage, () =>
                {
                    MessageManager.GetInstance().SendMsg1229();                 //发送退出消息
                });     
            }
            else
            {
                TooL.ShowNoticePage("您是房主，不能退出房间，请选择散桌！");
            }   
        }
        else
        {
            TooL.ShowNoticePage("游戏已经开始，不能退出房间，请选择散桌！");
        }
    }

    public void StartBtnClick()
    {
        if (isStart)
        {
            bool allReady = GameController.GetInstance().CheckAllReady();

            if (allReady && GameData.GetInstance().locationIndex == 0)
                MessageManager.GetInstance().SendMsg121();
            else
                SetStartBtn(0);
       
            isStart = false;
        }   
    }

    public void readyBtnClick()
    {
        if (isStart)
        {
            GameRoomController.GetInstance().ReadyBtnClickCallBack();
            MessageManager.GetInstance().SendMsg121(); //发送准备消息
            isStart = false;
        }
    }

    public void InviteBtnClick()
    {
        LoginAndShare.Controller.OnClickShareInfo(URLConst.ShareUrl);
    }

    //设置btn 的状态和UI显示
    public void SetStartBtn(int btnState)
    {
        GameRoomPage.GetInstance().SetBtnState(ButtonName.startBtn, btnState);
    }

    public void SetInviteBtn(int btnState)
    {
        GameRoomPage.GetInstance().SetBtnState(ButtonName.inviteBtn, btnState);
    }

    public void SetReadyBtn(int btnState)
    {
        GameRoomPage.GetInstance().SetBtnState(ButtonName.readyBtn, btnState);
    }

    public List<Button> btnList = new List<Button>();
    private void SetBtnState(ButtonName buttonName, int btnState)                  //btnState  0 不激活  1 激活允许点击 2激活不允许点击
    {
        if (!btnList[(int)buttonName].gameObject.activeInHierarchy &&  btnState != 0)
        {
            btnList[(int)buttonName].gameObject.SetActive(true);
        }

        if (btnState == 0)
        {
            btnList[(int)buttonName].GetComponent<Button>().interactable = false;
            btnList[(int)buttonName].gameObject.SetActive(false);
        }
        else if ( btnState == 1)
        {
            //ButtonChangeUI(buttonName, 1);
            btnList[(int)buttonName].GetComponent<Button>().interactable = true;
        }
        else if (btnState == 2)
        {
            //ButtonChangeUI(buttonName, 2);
            btnList[(int)buttonName].GetComponent<Button>().interactable = false;
        }
    }

    //private void ButtonChangeUI(ButtonName buttonName, int btnState)
    //{
    //    if (btnState == 1)
    //    {
    //        switch ((int)buttonName)
    //        {
    //            case 0:
    //                btnList[(int)buttonName].GetComponent<Image>().sprite = Resources.Load<Sprite>("BDUI/04/btn1");
    //                break;
    //            case 1:
    //                btnList[(int)buttonName].GetComponent<Image>().sprite = Resources.Load<Sprite>("BDUI/04/btn1");
    //                break;
    //            case 2:
    //                btnList[(int)buttonName].GetComponent<Image>().sprite = Resources.Load<Sprite>("BDUI/04/btn2");
    //                break;
    //        }
    //    }
    //    else if (btnState == 2)
    //    {
    //        switch ((int)buttonName)
    //        {
    //            case 0:
    //                btnList[(int)buttonName].GetComponent<Image>().sprite = Resources.Load<Sprite>("BDUI/04/btn3");
    //                break;
    //            case 1:
    //                btnList[(int)buttonName].GetComponent<Image>().sprite = Resources.Load<Sprite>("BDUI/04/btn3");
    //                break;
    //            case 2:
    //                btnList[(int)buttonName].GetComponent<Image>().sprite = Resources.Load<Sprite>("BDUI/04/btn3");
    //                break;
    //        }
    //    }
    //}

    public bool ShowDealPanel = false;
    //设置遮挡面板，播放动画时遮挡操作
    public void SetPanel(bool show)
    {
        if (show)
        {
            panel.gameObject.SetActive(true);
            ShowDealPanel = true;
        }
        else
        {
            panel.gameObject.SetActive(false);
            ShowDealPanel = false;
        }
    }

    public void SetAudAndPlay(int num)
    {
        aud.clip = clips[num];
        aud.Play();
    }

    public void SetAud2AndPlay(int num)
    {
        aud2.clip = clips[num];
        aud2.Play();
    }

    bool isStart = true;           //能够点击开始准备按钮
    float startTimer = 0;
    void Update()
    {
        if (!isStart)
        {
            startTimer += Time.deltaTime;
            if (startTimer > 2)
            {
                startTimer = 0;
                isStart = true;
            }
        }
    }
}
